//app.js
App({
  //初始化云开发
  onLaunch: function () {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: 'cloud1-7gch2pgze1a5eef2',
        traceUser: true,
      })
    }
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 路由全局拦截
    wx.onAppRoute(()=>{
      let currentRouter = getCurrentPages()[0].__route__;
      let userInfo = wx.getStorageSync('userInfo')
      console.log(currentRouter)
      if(!Object.keys(userInfo).includes('_openid') && currentRouter != 'pages/denglu/denglu'){
        wx.redirectTo({
          url: '/pages/denglu/denglu',
        })
      }
  });

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
    //获取当前时间戳  
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    console.log("当前时间戳为：" + timestamp);

    // 获取百度云拍照识物api
    this.getBaiduyunPicToken(timestamp)
    // 获取百度云OCRapi
    this.getBaiduyunTextToken(timestamp)

    wx.cloud.init({
      traceUser: true,
    })
    var _this = this;
    var logs = wx.getStorageSync('logs') || [];
    logs.unshift(Date.now());
    wx.setStorageSync('logs', logs);
    wx.login({
      success: function (_res) {}
    });
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              _this.globalData.userInfo = res.userInfo;
              if (_this.userInfoReadyCallback) {
                _this.userInfoReadyCallback(res.userInfo);
              }
            }
          });
        }
      }
    });

  },
  globalData: {
    userInfo: null,
    cashList: {}
  },
  getBaiduyunPicToken(timestamp) {
    var baiduyunPic = wx.getStorageSync("baiduyun_pic_AccessToken");
    console.log(baiduyunPic.access_token + " " + baiduyunPic.expires_in);
    if (baiduyunPic.access_token == "" || baiduyunPic.access_token == null || baiduyunPic.expires_in == "" || baiduyunPic.expires_in == null || baiduyunPic.expires_in < timestamp) {
      wx.request({
        url: "https://aip.baidubce.com/oauth/2.0/token",
        data: {
          grant_type: "client_credentials",
          client_id: "FBGsgolG3ccm72nUjKlcGexy",
          client_secret: "Iv9CxqZVw58KttiGEnM0gpgM6z4efePg"
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {
          //"Content-Type":"application/json"
          'content-type': 'application/x-www-form-urlencoded'
        }, // 设置请求的 header

        success: function (res) {
          wx.setStorageSync("baiduyun_pic_AccessToken", res.data);
        },
        fail: function (res) {
          // fail
          wx.showModal({
            title: "提示",
            content: "获取AccessToken出错，程序可能无法正常运行。",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {} else if (res.cancel) {}
            }
          })
        },
        complete: function (res) {
          // complete
        }
      });
    }
  },
  getBaiduyunTextToken(timestamp) {
    var baiduyunText = wx.getStorageSync("baiduyun_text_AccessToken");
    console.log(baiduyunText.access_token + " " + baiduyunText.expires_in);
    if (baiduyunText.access_token == "" || baiduyunText.access_token == null || baiduyunText.expires_in == "" || baiduyunText.expires_in == null || baiduyunText.expires_in < timestamp) {
      wx.request({
        url: "https://aip.baidubce.com/oauth/2.0/token",
        data: {
          grant_type: "client_credentials",
          client_id: "EmFZts1PWCuJAz3Qed5J8xNI",
          client_secret: "YwcP7ONND6pL2cLppD6d09C7QJL5Jozu"
        },
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {
          //"Content-Type":"application/json"
          'content-type': 'application/x-www-form-urlencoded'
        }, // 设置请求的 header

        success: function (res) {
          wx.setStorageSync("baiduyun_text_AccessToken", res.data);
        },
        fail: function (res) {
          // fail
          wx.showModal({
            title: "提示",
            content: "获取AccessToken出错，程序可能无法正常运行。",
            showCancel: false,
            success: function (res) {
              if (res.confirm) {} else if (res.cancel) {}
            }
          })
        },
        complete: function (res) {
          // complete
        }
      });
    }
  }
  /*getCashList: function (){
    const db = wx.cloud.database()
    db.collection('cashbook').field ({
      sid: true,
      _id: true
    }).get ({
      success: res => {
        let counterIds = new Array(res.data.length);*/
  /*res.data.forEach(function (item, index) {
    for (var i = 0; i < res.data.length; i++){
      counterIds[i] = item._id
    }
  })*/
  /*for (var i = 0; i < res.data.length; i++) {
          counterIds[i] = res.data[i]._id
        }
        console.log(counterIds)
        this.globalData.cashList  = {
          counterIds: counterIds
        }
      },
      fail: err => {
        wx.showToast ({
          icon: 'none',
          title: '查询记录失败'
        })
      }
    })
  }*/
})